package router

import (
	"net/http"
	"regexp"
	"strings"

	"github.com/PuerkitoBio/goquery"
	"github.com/gin-gonic/gin"
)

var enter int
var leave int

// Main 主函数
func Main(res *gin.Context) {
	code := res.Query("code")

	res.String(200, code)
}

// GetIP get ip
func GetIP() (string, string) {
	// ip地址
	dom, _ := goquery.NewDocument("http://ip.dhcp.cn/")
	node := dom.Find("body")
	var iptext string
	node.Each(func(i int, content *goquery.Selection) {
		iptext = content.Text()
	})
	// 地址
	dom, _ = goquery.NewDocument("http://ip.dhcp.cn/?ip=" + iptext)
	node = dom.Find("body")
	var addresstext string
	node.Each(func(i int, content *goquery.Selection) {
		addresstext = content.Text()
	})
	// 正则汉字
	var regS = regexp.MustCompile("[\u4E00-\u9FA5]+")
	var result = regS.FindAllString(addresstext, len(addresstext))
	// 返回IP地址 和 物理地址
	return iptext, result[0] + " " + result[1] + " " + result[2] + " " + result[3]
}

// Upload 上传头像
func Upload(res *gin.Context) {
	// 接收参数
	file, _ := res.FormFile("file")

	if file == nil {
		res.JSON(http.StatusOK, gin.H{
			"code": 200,
			"id":   0,
			"data": "",
			"msg":  "未获取到上传的文件",
		})
		return
	}

	var namearr = strings.Split(file.Filename, ".")
	var url = ""
	if namearr[1] == "jpg" || namearr[1] == "png" || namearr[1] == "ico" {
		url = "./public/upload/image/"
	} else {
		url = "./public/upload/file/"
	}
	var err = res.SaveUploadedFile(file, url+file.Filename)
	if err != nil {
		res.JSON(http.StatusOK, gin.H{
			"code": 200,
			"id":   0,
			"data": "",
			"msg":  "上传失败",
		})
		return
	}

	res.JSON(http.StatusOK, gin.H{
		"code": 200,
		"id":   1,
		"data": url + file.Filename,
		"msg":  "上传成功",
	})
}
